package cn.com.dashihui.api;

import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

import com.google.common.collect.Maps;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.Const;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.render.ViewType;
import com.jfinal.template.Engine;

import cn.com.dashihui.api.ITask.Cron4jPlugin;
import cn.com.dashihui.api.Quartz.GiveTask;
import cn.com.dashihui.api.asyncThread.AddTaskListTask;
import cn.com.dashihui.api.asyncThread.RabbitMQDownTask;
import cn.com.dashihui.api.asyncThread.RabbitMQUpTask;
import cn.com.dashihui.api.common.ESRedisPlugin;
import cn.com.dashihui.api.controller.AdController;
import cn.com.dashihui.api.controller.CommonController;
import cn.com.dashihui.api.controller.GoodsController;
import cn.com.dashihui.api.controller.GroupbuyingController;
import cn.com.dashihui.api.controller.OrderController;
import cn.com.dashihui.api.controller.OrderPayNotifyController;
import cn.com.dashihui.api.controller.SearchController;
import cn.com.dashihui.api.controller.StoreController;
import cn.com.dashihui.api.controller.UserController;
import cn.com.dashihui.api.dao.Ad;
import cn.com.dashihui.api.dao.ApiClient;
import cn.com.dashihui.api.dao.AuthSeller;
import cn.com.dashihui.api.dao.Bank;
import cn.com.dashihui.api.dao.Card;
import cn.com.dashihui.api.dao.Category;
import cn.com.dashihui.api.dao.Feedback;
import cn.com.dashihui.api.dao.Goods;

import cn.com.dashihui.api.dao.History;

import cn.com.dashihui.api.dao.GoodsSale;

import cn.com.dashihui.api.dao.Keyword;
import cn.com.dashihui.api.dao.Order;
import cn.com.dashihui.api.dao.OrderE;
import cn.com.dashihui.api.dao.OrderG;
import cn.com.dashihui.api.dao.OrderGLog;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.dao.OrderRefund;
import cn.com.dashihui.api.dao.OrderZ;
import cn.com.dashihui.api.dao.Seller;
import cn.com.dashihui.api.dao.Store;
import cn.com.dashihui.api.dao.StoreAd;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.dao.UserAddress;
import cn.com.dashihui.api.dao.UserCollection;
import cn.com.dashihui.api.dao.Version;
import cn.com.dashihui.api.handler.ContextParamsHandler;
import cn.com.dashihui.api.handler.SessionHandler;
import cn.com.dashihui.api.interceptor.AuthClientTokenInterceptor;
import cn.com.dashihui.api.interceptor.AuthLocationInterceptor;
import cn.com.dashihui.api.rabbitmq.MsgRecive;
import cn.com.dashihui.api.radisysnc.thread.RequestProcessorThreadPool;
import cn.com.dashihui.kit.ThreadPoolKit;

public class Config extends JFinalConfig {
	
	public void configConstant(Constants me) {
		// 如果生产环境配置文件存在，则优先加载该配置，否则加载开发环境配置文件
//		loadPropertyFile("config.local.properties");
		loadPropertyFile("config.properties");
//		loadPropertyFile("config.server.properties");
//		loadPropertyFile("config.test.properties");
		
	    //设置字符集
	    me.setEncoding("UTF-8");
	    me.setViewType(ViewType.JSP);
	    //调试模式，会打印详细日志
		me.setDevMode(getPropertyToBoolean("constants.devMode", false));
		//上传文件配置
		//注：此处的目录是上级目录，真正在Controller中获取上传的文件时，需要指定（也可以不指定）要将文件移到什么目录下（）相对于此处指定的目录
		//比如在此设置目录为<E:/>，而在Controller中<getFile("fileName","upload")>，则会将文件移至<E:/upload>目录中，如果不指定则移至<E:/>目录中
		//OreillyCos.init(PathKit.getWebRootPath()+File.separator+"upload", 10*1024*1024, "UTF-8");
	}
	
	/**
	 * 重写父类方法
	 */
	public Properties loadPropertyFile(String fileName) {
		PropKit.useFirstFound(fileName); 
		return loadPropertyFile(fileName, Const.DEFAULT_ENCODING);
	}
	
	public void configRoute(Routes me) {
		
		//设置视图根目录
		me.setBaseViewPath("/WEB-INF/page");
		me.add("/common", CommonController.class);
		me.add("/search", SearchController.class);
		//用户系列接口
		me.add("/user", UserController.class);
		//分公司系列接口
		me.add("/store", StoreController.class);
		//商品系列接口
		me.add("/goods", GoodsController.class);
		//广告位轮播图系列接口
		me.add("/ad", AdController.class);
		//商品订单系列接口
		me.add("/order", OrderController.class);
		me.add("/notify", OrderPayNotifyController.class);
		//团购系列接口
		me.add("/group", GroupbuyingController.class);

	}
	
	public void configPlugin(Plugins me) {

		//缓存
		EhCachePlugin ecp = new EhCachePlugin();
		me.add(ecp);
		 // 用于缓存news模块的redis服务 db.radisPath
	    RedisPlugin newsRedis = ESRedisPlugin.config();
	    if (newsRedis!=null) {
	    	me.add(newsRedis);
		}else {
			System.out.println("radis启动失败");
		}
	    
	    
	   
	    
		//定时任务
		Cron4jPlugin cp = new Cron4jPlugin("task.txt");//直接配置cron4j
		me.add(cp);
		// 配置C3p0数据库连接池插件
		C3p0Plugin c3p0Plugin = new C3p0Plugin(getProperty("db.jdbcUrl"), getProperty("db.username"), getProperty("db.password"), getProperty("db.jdbcDriver"));
		c3p0Plugin.setMaxPoolSize(getPropertyToInt("db.maxPoolSize"));
		c3p0Plugin.setMinPoolSize(getPropertyToInt("db.minPoolSize"));
		c3p0Plugin.setInitialPoolSize(getPropertyToInt("db.initialPoolSize"));
		c3p0Plugin.setMaxIdleTime(getPropertyToInt("db.maxIdleTime"));
		c3p0Plugin.setAcquireIncrement(getPropertyToInt("db.acquireIncrement"));
		me.add(c3p0Plugin);
		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		arp.setDialect(new MysqlDialect());
		//字段名大写
		arp.setContainerFactory(new CaseInsensitiveContainerFactory(false));
//		arp.setShowSql(true);
		me.add(arp);
		//添加model映射
		arp.addMapping("t_api_client", ApiClient.class);
		//公共轮播图
		arp.addMapping("t_bus_ad", Ad.class);
		//公共轮播图
		arp.addMapping("t_bus_ad", Ad.class);
		
		//公司信息表
		arp.addMapping("t_bus_seller", Seller.class);
		//分公司表
		arp.addMapping("t_dict_store", Store.class);
		//营业部信息表   同时也是商家端后台登录账号表
		arp.addMapping("t_auth_admin_seller", AuthSeller.class);
		
		
		//搜索关键字
		arp.addMapping("t_dict_keyword", Keyword.class);
		//用户表
		arp.addMapping("t_bus_user", User.class);
		//用户收藏表
		arp.addMapping("t_bus_user_collection", UserCollection.class);
		//历史记录
		arp.addMapping("t_bus_user_history", History.class);
		//用户收货地址
		arp.addMapping("t_bus_user_address", UserAddress.class);
		//商品分类
		arp.addMapping("t_dict_category", Category.class);
		//分公司商品表
		arp.addMapping("t_bus_goods", Goods.class);
		//商品规格表
		arp.addMapping("t_bus_goods_sale", GoodsSale.class);
		//分公司轮播图
		arp.addMapping("t_bus_store_ad", StoreAd.class);
		//商品订单系列
		arp.addMapping("t_bus_order", Order.class);
		arp.addMapping("t_bus_order_act", OrderE.class);
		arp.addMapping("t_bus_order_ecard", OrderZ.class);
		arp.addMapping("t_bus_order_gb", OrderG.class);
		arp.addMapping("t_bus_order_apirecord", OrderPayAPIRecord.class);
		arp.addMapping("t_bus_order_gb_log", OrderGLog.class);
		//用户付款相关信息表
		arp.addMapping("t_bus_user_card", Card.class);
		//银行以及对应Code
		arp.addMapping("t_bus_user_bank", Bank.class);
		//意见反馈及版本管理系列
		arp.addMapping("t_sys_feedback", Feedback.class);
		arp.addMapping("t_sys_version", Version.class);
		arp.addMapping("t_bus_order_refund", OrderRefund.class);
		
		
		
	}
	
	public void configInterceptor(Interceptors me) {
		
		me.add(new SessionInViewInterceptor());
		me.add(new AuthClientTokenInterceptor());
		//拦截判断用户是否定位或选择过分公司，如果没有，则跳转至定位页面
		me.add(new AuthLocationInterceptor());
		
	}
	
	public void configHandler(Handlers me) {
		/**
		 * 启动初始化线程池类
		 */
		RequestProcessorThreadPool.init();
		
		//可在此设置context_path，解决http://ip:port/context_path的问题
		//因为测试时是在jetty下，所以默认没有context_path，如果部署在tomcat下，会自动加上项目名，所以会用到该配置
		//可自定义context_path，默认下是CONTEXT_PATH，使用如：${CONTEXT_PATH}
		me.add(new ContextPathHandler("BASE_PATH"));

		//需要在页面传递的常量
		Map<String,Object> params = Maps.newHashMap();
		params.put("FTP_PATH", PropKit.get("constants.ftppath"));
		me.add(new ContextParamsHandler(params));
		me.add(new SessionHandler());
	}

	@Override
	public void configEngine(Engine me) {
		// TODO Auto-generated method stub
		
	}
	public void afterJFinalStart() {
		//Quartz
		GiveTask gt = new GiveTask();
		ThreadPoolKit.rabbitMQThreadPool.execute(new AddTaskListTask(gt));
//		//监听上架
		ThreadPoolKit.rabbitMQThreadPool.execute(new RabbitMQUpTask(gt));
//		//监听下架
		ThreadPoolKit.rabbitMQThreadPool.execute(new RabbitMQDownTask(gt));
		
	    /*
	     * 允许核心线程自动关闭
	     */
	    ThreadPoolKit.teamThreadPool.allowCoreThreadTimeOut(true);
	}
}
